<template>
  <el-dialog :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="1000px" @open="open" @close="close">
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="100px" :disabled="disableEditSubmit">
      <br v-if="parentName !== 'allFeedback' && parentName !== 'feedbackList'">
      <el-row v-if="parentName !== 'allFeedback' && parentName !== 'feedbackList'">
        <el-steps :active="lastPhase" finish-status="success" process-status="finish" align-center>
          <el-step title="提交反馈"></el-step>
          <el-step title="负责人分发"></el-step>
          <el-step title="办理人解决"></el-step>
          <el-step title="负责人确认"></el-step>
        </el-steps>
      </el-row>
      <br v-if="parentName !== 'allFeedback' && parentName !== 'feedbackList'">
      <el-row>
        <div class="tl-form-line-title">
          问题描述
        </div>
        <el-col :span="24">
          <el-form-item prop="content" label-width="28px" :rules="rules.validateRequire">
            <el-input v-model="model.content" type="textarea" :rows="4" :disabled="disabledEdit"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="lastPhase !== 0">
        <div class="tl-form-line-title">
          问题回复
        </div>
        <el-col :span="24">
          <el-form-item label-width="28px">
            <el-scrollbar :style="{ 'max-height': 96 + 'px', 'overflow-x': 'hidden', 'background-color': '#f5f7fa' }">
              <div style="padding: 10px 5px; height: 96px;">
                <div v-if="response.length > 0">
                  <div style="margin-bottom: 10px" v-for="item in response" :key="item.id">
                    <div style="margin-left: 12px;  margin-top: -2px; line-height: 1.5;">回复内容：{{ item.dealpersonsuggestion }}</div>
                    <div class="response-time">时间：{{ item.createon }}</div>
                  </div>
                </div>
                <div style="margin-left: 12px;  margin-top: -10px;" v-else>暂无回复</div>
              </div>
            </el-scrollbar>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <div class="tl-form-line-title">
          反馈相关
        </div>
        <el-col :span="12">
          <el-form-item label="问题等级" prop="questionlevel" :rules="rules.validateRequire" v-if="isManager">
            <el-select v-model="model.questionlevel" :disabled="disabledHistoryEdit"  placeholder="请选择问题等级" clearable>
              <el-option v-for="item in codeModel.feedbackQuestionLevelList" :key="item.code" :label="item.name" :value="item.code"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否公开" prop="ispublic" :rules="rules.validateRequire" v-if="isManager">
            <el-select v-model="model.ispublic" :disabled="disabledHistoryEdit"  placeholder="请选择是否公开" clearable>
              <el-option v-for="item in codeModel.feedbackIsPublicList" :key="item.code" :label="item.name" :value="item.code"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
         <el-col :span="12" v-if="belongToBpa">
          <el-form-item label="所属业务" prop="belongbusiness" :rules="rules.validateRequire">
            <el-select v-model="model.belongbusiness" placeholder="请选择所属业务" :disabled="disabledEdit" @change="changeDealPerson" filterable clearable>
              <el-option v-for="item in codeModel.businessTypeList" :key="item.code" :label="item.name" :value="item.code"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-else>
          <el-form-item label="业务类型" prop="servicetype" :rules="rules.validateRequire">
            <el-select v-model="model.servicetype" placeholder="请选择业务类型" :disabled="disabledEdit" @change="changeDealPerson" filterable clearable>
              <el-option v-for="item in codeModel.feedbackServiceTypeList" :key="item.code" :label="item.name" :value="item.code"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!belongToBpa">
          <el-form-item label="所属系统" prop="system" :rules="rules.validateRequire">
            <el-select v-model="model.system"  placeholder="请先选择业务类型" :disabled="disabledEdit" @change="changeDealPerson" filterable clearable>
              <el-option v-for="item in feedbackSystemList" :key="item.code" :label="item.name" :value="item.code"/>
            </el-select>
          </el-form-item>
        </el-col>
           <el-col :span="12">
          <el-form-item label="反馈类型" prop="feedbacktype" :rules="rules.validateRequire">
            <el-select v-model="model.feedbacktype" @focus='filterItem' placeholder="请选择反馈类型" :disabled="disabledEdit" @change="changeDealPerson" filterable clearable>
              <el-option v-for="item in codeModel.feedbackTypeList" :key="item.code" :label="item.name" :value="item.code"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属负责人" prop="systemresponsiblecode" :rules="rules.validateRequire">
            <el-input v-model="dispSystemResponsible" placeholder="请先选择反馈类型、业务类型和所属系统" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发生时间" prop="faulttime" v-if="model.faulttime || isBugType">
            <el-date-picker v-model="model.faulttime" type="datetime" :picker-options="timePickerOptions" placeholder="请选择发生时间"  value-format="yyyy-MM-dd HH:mm" format=" yyyy-MM-dd HH:mm" :disabled="disabledEdit"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <tl-approval-history ref="history" sourceType="MmsSuggestionFeedback" :sourceId="model.id" />
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="lastPhase === 0 || isManager === true" >保存</el-button>
      <el-button type="primary" @click="doSubmitApproval" v-if="lastPhase === 0" :loading="saveLoading" >提交</el-button>
      <el-button type="danger" @click="doDelete(model.id)" v-if="lastPhase === 0" :loading="saveLoading" >删除</el-button>
      <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory" v-if="parentName !== 'allFeedback'" ><svg-icon icon-class="list" />审批历史</el-button>
      <tl-attachment source-type="MmsSuggestionFeedback" :source-id="model.id" :editable="lastPhase === 0"  :limit-type="limitType" :limit-count="4"></tl-attachment>
    </div>
  </el-dialog>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
/** 子组件 */
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import { MMS_FEEDBACK_TYPE } from '@/const/const'
import { MMS_SYSTEM_TYPE } from '@/const/const'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: { },
  data() {
    return {
      moduleTitle: '意见反馈',
      urlPrefix: '/mms/suggestionFeedback/',
      url: {
        // 额外的url
        querySystemAndResponsible: '/mms/baseConfig/list',
        feedbackInfo: '/mms/suggestionFeedback/feedbackInfo',
        queryResponse: '/mms/response/responseList',
        delete: '/mms/suggestionFeedback/delete'
      },
      systemInfo: [],
      lastPhase: 0,
      response: [],
      tempResponse: [],
      isDisplayButton: false,
      disabledEdit: true,
      isManager: false,
      disabledHistoryEdit: false,
      isBugType: false,
      limitType: "png,bmp,jpg,jpeg,gif,tiff,svg",
      parentName: '',
      dispSystemResponsible: '',
      feedbackSystemList: [],
      timePickerOptions: {
        disabledDate: (date) => {
          return new Date(date).getTime() > new Date().getTime()
        }
      }
    }
  },
  computed: {
    /** 判断当前意见反馈是否从流程文档进入 */
    bpaSystemFlag() {
      return this.$store.getters.microGlobalParam.systemFlag === 'bpa'
    },
		/** 判断当前反馈所属系统是否为流程文档 */
		belongToBpa() {
      return this.model && this.model.system && this.model.system === MMS_SYSTEM_TYPE.cdmc
		}
  },
  methods: {
    /** 过滤反馈类型数据 */
    filterItem() {
      if (this.belongToBpa) {
        // 如果是流程文档，只保留流程建设和流程优化
        this.codeModel.feedbackTypeList = this.codeModel.feedbackTypeList.filter(item => item.code === MMS_FEEDBACK_TYPE.processOptimization || item.code === MMS_FEEDBACK_TYPE.processConstruction)
      } else {
        this.codeModel.feedbackTypeList = this.codeModel.feedbackTypeList.filter(item => item.code !== MMS_FEEDBACK_TYPE.processConstruction)
			}
    },
    /** 单个删除数据 */
    doDelete(id) {
      if (!this.url.delete) {
        this.$tap.alert('请设置delete地址!', 'warning')
        return
      }
      this.saveLoading = true
      this.$tap
        .confirm('确定删除数据吗？')
        .then((_) => {
          deleteAction(this.url.delete, { ids: id }).then((res) => {
            if (res.success) {
              this.$tap.message(res.message, 'success')
              this.visible = false
            } else {
              this.$tap.alert(res.message, 'warning')
            }
            this.$emit("refresh")
            this.saveLoading = false
          })
        })
        .catch((_) => {
          this.saveLoading = false
        })
    },
    doSubmitApproval() {
      if (!this.url.submit) {
        this.$tap.alert('请设置审批地址!', 'warning')
        return
      }
      let fileValidate = true
      this.$refs.form.validate((valid) => {
        if (!valid) {
          fileValidate = false
        }
      })
      if (!fileValidate) {
        return
      }
      this.saveLoading = true
      this.$tap
        .confirm('确定提交审批吗？提交后，单据内容不可修改！')
        .then((_) => {
          if (!this.beforeApproval()) {
            this.saveLoading = false
            return
          }
          putAction(this.url.submit, this.model).then((res) => {
            if (res.success) {
              this.$tap.message(res.message, 'success')
              this.queryData(this.model.id)
              this.afterApproval()
              this.visible = false
            } else {
              this.$tap.alert(res.message, 'warning')
            }
            this.$emit("refresh")
            this.saveLoading = false
          })
        })
        .catch((_) => {
          this.$emit("refresh")
          this.saveLoading = false
        })
    },
    querySystemAndResponsible() {
      let qryParam = {}
      // 只有是从流程文档跳入的页面会触发参数传给后端获取数据
      if (this.belongToBpa) {
        qryParam.qry_system = MMS_SYSTEM_TYPE.cdmc
      }
      getAction(this.url.querySystemAndResponsible, qryParam)
        .then((res) => {
          if (res.success) {
            this.systemInfo = res.result.dataList
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterLoadData()
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    changeDealPerson() {
      // 清空所属负责人
      this.$set(this.model, 'systemresponsiblecode', '')
      this.$set(this.model, 'systemresponsiblename', '')
			// 如果属于流程文档，匹配所属负责人
      if (this.belongToBpa) {
        // 选中所属业务才可遍历系统配置表
        if (this.model.belongbusiness) {
          for (var i in this.systemInfo) {
             if (this.systemInfo[i].belongbusiness && this.systemInfo[i].belongbusiness === this.model.belongbusiness) {
              this.$set(this.model, 'systemresponsiblecode', this.systemInfo[i].systemresponsiblecode)
              this.$set(this.model, 'systemresponsiblename', this.systemInfo[i].systemresponsiblename)
              this.dispSystemResponsible = this.systemInfo[i].systemresponsiblename + '[' + this.systemInfo[i].systemresponsiblecode + ']'
            }
          }
        }
      } else {
         this.dispSystemResponsible = ''
        // 只有已配置系统的业务类型，所属系统才有值
        this.feedbackSystemList = []
        if (this.model.servicetype) {
          this.systemInfo.forEach(item => {
            if (item.servicetype && item.servicetype.includes(this.model.servicetype)) {
              this.codeModel.feedbackSystemList.forEach(systemItem => {
                if (!this.feedbackSystemList.includes(systemItem) && systemItem.code === item.system) {
                  this.feedbackSystemList.push(systemItem)
                }
              })
            }
          })
          if (this.feedbackSystemList.length === 0) {
            this.$set(this.model, 'system', '')
          }
        }
        // 所属负责人
        if (this.model.feedbacktype && this.model.servicetype && this.model.system) {
          this.systemInfo.forEach(item => {
            if (item.feedbacktype.includes(this.model.feedbacktype) && item.servicetype.includes(this.model.servicetype) && item.system.includes(this.model.system)) {
              this.$set(this.model, 'systemresponsiblecode', item.systemresponsiblecode)
              this.$set(this.model, 'systemresponsiblename', item.systemresponsiblename)
              this.dispSystemResponsible = item.systemresponsiblename + '[' + item.systemresponsiblecode + ']'
            }
          })
        }
      }
      // BUG类型需要填写错误发生时间
      if (this.model.feedbacktype === '1') {
        this.isBugType = true
      } else {
        this.isBugType = false
        this.$set(this.model, 'faulttime', '')
      }
    },
    afterSubmit() {
      // 管理员保存后关闭对话框
      if (this.isManager) {
        this.close()
      }
    },
    close() {
      this.response = []
      this.isDisplayButton = false
      this.lastPhase = 0
      this.disabledEdit = true
      this.isBugType = false
      this.visible = false
      this.dispSystemResponsible = ''
      this.$emit("refresh")
    },
    loaded() {
      this.queryResponse()
      this.findLastPhase()
      this.querySystemAndResponsible()
      this.dispSystemResponsible = this.model.dispsystemperson
      if (this.lastPhase === 0) {
        this.disabledEdit = false
        this.title = '编辑' + this.moduleTitle
      } else {
        this.disabledEdit = true
        this.title = '查看' + this.moduleTitle
      }
      // 管理员打开页面，标题显示
      if (this.isManager) {
        this.title = '编辑' + this.moduleTitle
      }
      if (this.model.feedbacktype === '0') {
        this.isBugType = true
      } else {
        this.isBugType = false
      }
      // 审批阶段或审批完成阶段
      if (this.lastPhase !== '0') {
        this.feedbackSystemList = this.codeModel.feedbackSystemList
      }
    },
    queryResponse() {
      let param = {
        qry_sourcetype: 'MmsSuggestionFeedback',
        qry_sourceid: this.id
      }
      getAction(this.url.queryResponse, param).then((res) => {
        if (res.success) {
          if (res.result.length) {
            this.response.push(res.result[0])
          }
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    // 判断当前流程的最新阶段
    findLastPhase() {
      switch (this.model.latestphase) {
        case '开始':
          this.lastPhase = 0
          break
        case '负责人分发':
          this.lastPhase = 1
          break
        case '办理人':
          this.lastPhase = 2
          break
        case '负责人确认':
          this.lastPhase = 3
          break
        case '结束':
          this.lastPhase = 4
          break
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.response-content {
  font-family: '思源黑体 CN', sans-serif;
  font-weight: 400;
  font-style: normal;
  font-size: 13px;
  color: rgba(102, 102, 102, 0.996078431372549);
  line-height: 20px;
}
.response-time {
  font-family: '苹方-简 中等', '苹方-简', sans-serif;
  font-weight: 400;
  font-style: normal;
  font-size: 9px;
  color: #909399;
  height: 15px;
  line-height: 15px;
  vertical-align: middle;
  margin-left: 12px;
}
.text-button {
  font-family: '苹方-简 中等', '苹方-简', sans-serif;
  font-weight: 400;
  font-style: normal;
  font-size: 9px;
  color: #909399;
  height: 15px;
  line-height: 15px;
  vertical-align: middle;
  color: #0A6ED2;
  &:hover {
    cursor: pointer;
  }
}
</style>

